/**
 * 
 */
package com.tvshows.interactions;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.tvshows.front.controllers.favorite.FavoriteController;
import com.tvshows.front.listener.command.RefreshJob;
import com.tvshows.front.ui.recap.TableCompositeRecapUI;
import com.tvshows.front.ui.refresh.RefreshUI;
import com.tvshows.structure.bdd.BddQueries;
import com.tvshows.structure.beans.Favorite;
import com.tvshows.structure.log.LoggingTreatment;
import com.tvshows.structure.patterns.UrlConstructor;
import com.tvshows.structure.reader.FileOperations;

/**
 * @author tMidy
 * <p>
 * Class used to Refresh the favorites list
 * </p>
 */
public class ObserverBdd
{

    private FavoriteController listFavorite;

    private TableCompositeRecapUI tableRecap;

    private static ObserverBdd observerBdd;

    private final UrlConstructor constructor;

    private List<Favorite> favorites;

    private String formattedEpisode;

    private final Logger logger = Logger.getLogger( ObserverBdd.class );

    private RefreshUI refreshUI;

    /**
     * Constructeur
     */
    private ObserverBdd()
    {
        constructor = new UrlConstructor();
    }

    /**
     * Refresh the favorite list
     */
    public void reloadListFavorite()
    {
        listFavorite.loadFavorites();
        listFavorite.activeDeleteOnFavorite();
    }

    /**
     * Loads the Favorite shows
     * 
     * @param refreshJob the refreshJob
     * @throws Exception
     */
    public void loadFavoriteDownload( RefreshJob refreshJob )
        throws Exception
    {
        LoggingTreatment.getInstance().logInfo( logger, " Récupération de la table des favoris..." );
        favorites = BddQueries.getBddQueries().loadFavorites();
        if ( favorites.size() != 0 )
        {
            LoggingTreatment.getInstance().logInfo( logger, " Insertion des torrents en download" );

            synchronized ( favorites )
            {
                for ( Iterator<Favorite> it = favorites.iterator(); it.hasNext(); )
                {
                    Favorite favorite = it.next();

                    constructor.constructUrl( favorite.getNameFavorite(), favorite.getSeasonNumber(),
                        favorite.getLastEpisodeNumber() );
                    LoggingTreatment.getInstance().logInfo( logger,
                        " chargement du favori " + favorite.getNameFavorite() );

                    if ( constructor.getUrlToAdd() != null )
                    {
                        refreshJob.addToTable( favorite );
                        LoggingTreatment.getInstance().logInfo( logger,
                            " Fichier trouvé pour " + favorite.getNameFavorite() );

                        launchProcess( constructor.getUrlToAdd() );
                        formattedEpisode = formatEpisode( favorite.getLastEpisodeNumber() );
                        BddQueries.getBddQueries().updateFavoriteEpisode( favorite.getNameFavorite(), formattedEpisode );
                    }

                    refreshJob.updateStatus();

                }
            }
            LoggingTreatment.getInstance().logInfo( logger, "Insertion des torrents en download OK!" );
        }
    }

    /**
     * Add to table
     * 
     * @throws Exception
     */
    public void addToTable( Favorite favorite )
        throws Exception
    {
        tableRecap.addToTable( constructor.getTitle() + " season " + favorite.getSeasonNumber() + " episode "
            + favorite.getLastEpisodeNumber() );
    }

    /**
     * Updates the progress bar
     */
    public void updateProgress()
    {
        int progress = 100 / favorites.size();
        if ( !refreshUI.isSelection() )
        {
            refreshUI.setSelection( progress * favorites.size() );
        }
        refreshUI.updateProgress( progress );
        refreshUI.updateProgressLabel( (double) 100 / favorites.size() );
    }

    /**
     * Activates or not the progress bar
     * 
     * @param activate isActive?
     */
    public void activate( boolean activate )
    {
        refreshUI.activateProgressBar( activate );
    }

    /**
     * @param episode
     * @return the formatted value of the new episode to load
     */
    private String formatEpisode( String episode )
    {
        int formatted = Integer.parseInt( episode ) + 1;
        if ( formatted < 10 )
        {
            return "0" + formatted;
        }
        return String.valueOf( Integer.parseInt( episode ) + 1 );
    }

    /**
     * Launch refresh process
     * 
     * @param urlToAdd the link to add
     * @throws IOException
     */
    private void launchProcess( String urlToAdd )
        throws IOException
    {
        Runtime runtime = Runtime.getRuntime();
        List<String> properties = FileOperations.getInstance().readProperties();
        if ( !properties.isEmpty() )
        {
            String softwarePath = properties.get( 0 );
            runtime.exec( softwarePath + " " + urlToAdd.replace( " ", "." ) );
        }
    }

    /**
     * @return the listFavorite
     */
    public FavoriteController getListFavorite()
    {
        return listFavorite;
    }

    /**
     * @param listFavorite the listFavorite to set
     */
    public void setListFavorite( FavoriteController listFavorite )
    {
        this.listFavorite = listFavorite;
    }

    /**
     * @return the tableRecap
     */
    public TableCompositeRecapUI getTableRecap()
    {
        return tableRecap;
    }

    /**
     * @param tableRecap the tableRecap to set
     */
    public void setTableRecap( TableCompositeRecapUI tableRecap )
    {
        this.tableRecap = tableRecap;
    }

    /**
     * @return the observerBdd
     */
    public static ObserverBdd getObserverBdd()
    {
        if ( observerBdd == null )
        {
            observerBdd = new ObserverBdd();
        }
        return observerBdd;
    }

    /**
     * Activates the ability to delete
     */
    public void activeDeleteOnFavorite()
    {
        listFavorite.activeDeleteOnFavorite();
    }

    /**
     * @return the selected favorite
     */
    public String getSelectedFavorite()
    {
        return listFavorite.getSelectedFavorite();
    }

    /**
     * return the search results of the title entered
     */
    public Hashtable<String, String> loadSearchResults( String paramName )
    {
        return constructor.getFeeds( paramName );
    }

    /**
     * @param refreshView
     */
    public void setRefreshView( RefreshUI refreshView )
    {
        this.refreshUI = refreshView;
    }

    /**
     * returns the refreshUI
     */
    public RefreshUI getRefreshUI()
    {
        return this.refreshUI;

    }
}
